<template>
  <div>
    <h1>{{id?'编辑':'新建'}}物品</h1>
    <el-form @submit.native.prevent="saveArticle" ref="form" :model="model" label-width="80px">
      
      <el-form-item label="名称">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <!-- :action="$http.defaults.baseURL + 'upload'" -->
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :headers='getHeader()'
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="model.img" :src="model.img" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>


<script>
  export default {
    props:{
      id:{}
    },
    data() {
      return {
        model: {},
        parentOptions:[],
        imageUrl: ''
      }
    },
    created() {
      this.id && this.feach();
      
    },
    methods: {
      async feach(){
        const res = await this.$http.get(`rest/items/${this.id}`)/* .then(res=>{
          console.log(res.data);
          this.model=res.data
        }) */
        this.model=res.data
      },
      onSubmit() {
        console.log('start!');
      },
      async saveArticle(){
        let res
        if (this.id) {//编辑
          res = await this.$http.put(`rest/items/${this.id}`,this.model)
        }else{//新建
          res = await this.$http.post('rest/items',this.model)
        } 
        this.$router.push('/items/list')
        console.log(res.data);
        this.$message({
            message: '保存成功',
            type: 'success'
        });
      },
      handleAvatarSuccess(res) {
        console.log('图片上传服务器');
        this.$set(this.model,'img',res.url)//显示赋值
        //this.model.img=res.url
        //this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>
<style lang="css">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px !important;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>